<?php
namespace frontend\modules\Api\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use yii\filters\AccessControl;
use common\services\UploadService;
use yii\web\UploadedFile;

/**
 * Class UploadController
 * @package frontend\modules\Api\controllers
 * 上传相关
 */
class UploadController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }




    public function actionUploadLocal(){
        $file = UploadedFile::getInstanceByName('file');
        $savePath = 'uploads/'.date('His') . md5(uniqid()) . '.' . $file->getExtension();
        if($file->saveAs($savePath)){
            return self::successResponse();
        }
        return self::failureResponse();
    }

    /**
     * @throws \yii\base\ExitException
     * @desc 文件上传
     */
    public function actionFile()
    {
        if(empty($_FILES)) {
            return self::failureResponse(500, '未检测到上传文件');
        }
        $imgList = current($_FILES);
        // 执行上传
        if(is_string($imgList['tmp_name'])) {
            $fileSuffix = end(explode('.', $imgList['name']));
            $fileSuffix = strtolower($fileSuffix);
            // 上传预先检查
            $this->checkFileValidSignal($imgList['tmp_name'],$fileSuffix);
            // 执行单个文件上传
            $uploadKey  = date('Y-m-d').'-'.uniqid().'.'.$fileSuffix;
            $ret        = UploadService::putFile($imgList['tmp_name'],$uploadKey);
            if (!$ret) {
                return self::failureResponse(500,'上传出错:'.UploadService::getError());
            }
            $url = getenv('QINIU_IMG_DOMAIN').$ret['key'];
            return self::successResponse(['url'=>$url]);
        }else {
            $result = [] ;
            // 最终执行上传
            foreach ($imgList['tmp_name'] as $tk => $tmp) {
                $fileSuffix = end(explode('.', $imgList['name'][$tk]));
                $fileSuffix = strtolower($fileSuffix);
                // 上传预先检查
                $this->checkFileValidSignal($tmp,$fileSuffix);
                // 上传逻辑
                $uploadKey  = date('Y-m-d').uniqid().'.'.$fileSuffix;
                $ret        = UploadService::putFile($tmp,$uploadKey);
                if (!$ret) {
                    return self::failureResponse(500,'上传出错:'.UploadService::getError());
                }
                $result[] = getenv('QINIU_IMG_DOMAIN').$ret['key'];
            }
            return self::successResponse(['url_list'=>$result]);
        }
    }

    /**
     * @throws
     * 图片上传 支持单文件/多文件上传 最多同时6文件 表单提交 多文件[]
     * 单张小于3m
     */
    public function actionImg()
    {
        if(empty($_FILES)) {
            return self::failureResponse(500, '未检测到图片');
        }
        $imgList = current($_FILES);
        // 上传预先检查
        $this->checkImgValid($imgList['tmp_name']);
        // 执行上传
        if(is_string($imgList['tmp_name'])) {
            // 执行单个文件上传
            $uploadKey  = uniqid().'.png';
            $ret        = UploadService::putFile($imgList['tmp_name'],$uploadKey);
            if (!$ret) {
                return self::failureResponse(500,'上传出错:'.UploadService::getError());
            }
            $url = getenv('QINIU_IMG_DOMAIN').$ret['key'];
            return self::successResponse(['url'=>$url]);
        }else {
            $result = [] ;
            // 最终执行上传
            foreach ($imgList['tmp_name'] as $tmp) {
                // 上传逻辑
                $uploadKey  = uniqid().'.png';
                $ret        = UploadService::putFile($tmp,$uploadKey);
                if (!$ret) {
                    return self::failureResponse(500,'上传出错:'.UploadService::getError());
                }
                $result[] = getenv('QINIU_IMG_DOMAIN').$ret['key'];
            }
            return self::successResponse(['url_list'=>$result]);
        }
    }

    /**
     * @param $img
     * @throws
     * @return mixed
     * 检查上传图片是否符合要求
     */
    private function checkImgValid($img)
    {
        if(is_array($img)){
            if(count($img) > 6) {
                return self::failureResponse(500, '最多可上传6张图片');
            }
            foreach ($img as $tmp) {
                $this->checkImgValidSignal($tmp);
            }
        }else{
            $this->checkImgValidSignal($img);
        }
        return true ;
    }

    /**
     * @param $img
     * @throws \yii\base\ExitException
     * @return mixed
     */
    private function checkImgValidSignal($img)
    {
        $maxSize    = 3 * 1024 * 1024 ;
        $allowMime  = ['image/png','image/jpeg','image/gif'];
        $info       = getimagesize($img);
        if(!in_array($info['mime'],$allowMime)){
            return self::failureResponse(500, '图片格式支持png,jpg,gif');
        }
        $fileSize   = filesize($img);
        if($fileSize > $maxSize) {
            return self::failureResponse(500, '单文件大小不得超过3M');
        }
        return true;
    }

    /**
     * @param $file
     * @param $fileSuffix string 文件后缀
     *
     * @return mixed
     * @throws \yii\base\ExitException
     * @desc 检查单个文件是否符合上传约束
     */
    private function checkFileValidSignal($file,$fileSuffix)
    {
        $maxSize     = 5 * 1024 * 1024 ;
        $allowSuffix = ['png','jpg','gif','jpeg','doc','docx','xls','xlsx','pptx','ppt','pdf','zip','rar','tar','gz','7z','txt','xml'] ;
        if(!in_array($fileSuffix,$allowSuffix)){
            return self::failureResponse(500, '文件格式不被允许');
        }
        $fileSize   = filesize($file);
        if($fileSize > $maxSize) {
            return self::failureResponse(500, '单文件大小不得超过5M');
        }
        return true;
    }
}
